package org.gjy.m8.concurrent;

import com.google.common.collect.Lists;
import com.googlecode.aviator.AviatorEvaluator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-06-30 15:11:25
 */
public class SemaphoreTest {
    private static final Logger log = LoggerFactory.getLogger(SemaphoreTest.class);

    public static void main(String[] args) {
        List<String> list = Lists.newArrayList("1+1", "99*12+122-12", "883-21", "90/25", "1+1+12", "99*12+122+12", "883+21", "90+25");
        CopyOnWriteArrayList<Object> result = new CopyOnWriteArrayList<>();
        ThreadPoolExecutor pool = ThreadPoolUtil.getDefaultPool();
        Semaphore semaphore = new Semaphore(3);
        try {
            for (String s : list) {
                pool.submit(() -> {
                    try {
                        semaphore.acquire();
                        Object execute = AviatorEvaluator.compile(s).execute();
                        TimeUnit.SECONDS.sleep(1);
                        result.add(execute);
                        log.info("算费: {}={}", s, execute);
                    } catch (InterruptedException e) {
                        log.error("算费失败: {}", e.getMessage());
                    } finally {
                        semaphore.release();
                    }

                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            ThreadPoolUtil.shutdown(pool);
        }

    }

}
